package com.pickup.netty.server.handler;

import com.pickup.netty.controller.SocketController;
import com.pickup.netty.message.NettyData;

import com.pickup.netty.util.MethodMapping;
import com.pickup.utils.JsonUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;


@Slf4j
public class ChatInboundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private SocketController socketController = new SocketController();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        String content = msg.text();
        NettyData nettyData = JsonUtils.jsonToPojo(content, NettyData.class);
        Method targetMethod = MethodMapping.mappingTo(nettyData.getAction());
        targetMethod.invoke(socketController, nettyData, ctx, msg);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        users.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        users.remove(ctx.channel());
        //SessionFactory.getSession().unbind(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //cause.printStackTrace();
        ctx.channel().close();
        users.remove(ctx.channel());
        //SessionFactory.getSession().unbind(ctx.channel());
    }


}
